package net.liteheaven.xblib.plugin;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

/**
 * 插件代理Activity基类
 *
 * Created by LiangYu on 16/8/29
 */
public class XProxyActivity extends FragmentActivity{

    private XPlugin mXPlugin;

    private boolean mInit = true;

    public XProxyActivity(){
        super();
    }

    @Override
    public AssetManager getAssets() {
        AssetManager proxy = mXPlugin != null ? mXPlugin.getAssetManager() : null;
        proxy = mInit ? proxy : null;
        return proxy == null ? super.getAssets() : proxy;
    }

    @Override
    public Resources getResources() {
        Resources proxy = mXPlugin != null ? mXPlugin.getResources() : null;
        proxy = mInit ? proxy : null;
        return proxy == null ? super.getResources() : proxy;
    }

    @Override
    public Resources.Theme getTheme() {
        Resources.Theme proxy = mXPlugin != null ? mXPlugin.getTheme() : null;
        proxy = mInit ? proxy : null;
        return proxy == null ? super.getTheme() : proxy;
    }

    protected String getPluginActivityName(){
        Intent intent = getIntent();
        if (intent != null){
            return intent.getStringExtra(XPluginConst.PLUGIN_ACTIVITY_NAME);
        }
        return "";
    }

    protected String getPluginName(){
        Intent intent = getIntent();
        if (intent != null){
            return intent.getStringExtra(XPluginConst.PLUGIN_NAME);
        }
        return "";
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        // 解决4.x编译器问题
        // Class ref in pre-verified class resolved to unexpected implementation
        PluginKit.getInstance().setContext(getApplicationContext());
    }

    // 测试：不同的ClassLoader，使用同一个类没有问题
    private static int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        System.out.println("### " + i++);

        String pluginName = getPluginName();
        if (!TextUtils.isEmpty(pluginName)){
            try {
                mXPlugin = PluginKit.getInstance().getManager().get(pluginName);
                mXPlugin.attachActivity(this);
            } catch (XPluginException e) {
                XPluginLog.i(e);
            }
        }
    }
}
